import storage from '/imports/utils/storage'
import { Users } from '/imports/collections'
import { Meteor } from 'meteor/meteor'
import { setTimeoutAsync } from '/imports/utils/common'

export default async function ({ state, commit }) {
  //
  let userId = storage.getItem('userId')

  if (userId) {
    // 订阅初始ID对应用户
    const subscribe = Meteor.subscribe('users.login_by_token', { _id: userId })

    // 等待订阅完成
    while (!subscribe.ready()) {
      await setTimeoutAsync(10)
    }
    let user = Users.findOne()

    if (user) {
      commit('updateUserData', user)
    }

    subscribe.stop()
  }
}
